# coding=utf-8
# 编译日期：2023-02-06 10:37:27
# 版权所有：www.i-search.com.cn
import datetime
import ubpa.init_input as iinput
from ubpa.base_util import StdOutHook, ExceptionHandler
import ubpa.iexcel as iexcel
import ubpa.ifile as ifile
import ubpa.itools.rpa_environment as rpa_environment
import ubpa.iedge as iedge
import ubpa.ics as ics
import ubpa.iwin as iwin
import ubpa.ibrowse as ibrowse
import time
import pdb
from ubpa.ilog import ILog
import getopt
from sys import argv
import sys
import os
from ubpa.base_img import *

class GetBaiduRankList:
     
    def __init__(self,**kwargs):
        self.__logger = ILog(__file__)
        self.path = set_img_res_path(__file__)
        self.robot_no = ''
        self.proc_no = ''
        self.job_no = ''
        self.input_arg = ''
        if('robot_no' in kwargs.keys()):
            self.robot_no = kwargs['robot_no']
        if('proc_no' in kwargs.keys()):
            self.proc_no = kwargs['proc_no']
        if('job_no' in kwargs.keys()):
            self.job_no = kwargs['job_no']
        ILog.JOB_NO, ILog.OLD_STDOUT = self.job_no, sys.stdout
        sys.stdout = StdOutHook(self.job_no, sys.stdout)
        ExceptionHandler.JOB_NO, ExceptionHandler.OLD_STDERR = self.job_no, sys.stderr
        sys.excepthook = ExceptionHandler.handle_exception
        if('input_arg' in kwargs.keys()):
            self.input_arg = kwargs['input_arg']
            if(len(self.input_arg) <= 0):
                self.input_arg = iinput.load_init(__file__)
            if self.input_arg is None:
                sys.exit(0)
            self.keyword = iinput.get_par(self.input_arg, 'keyword')
      
    def Main(self):
        title=1
        file=None
        #打开浏览器
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:202212141600554779,Title:打开浏览器,Note:请确保已安装edge浏览器及插件.未安装时，可修改“目标属性”中的浏览器类型')
        tvar_2022121416005547810=ibrowse.open_browser(browser_type='edge',url='www.baidu.com')
        print('[Main] [打开浏览器] [SNTag:202212141600554779]  返回值：[' + str(type(tvar_2022121416005547810)) + ']' + str(tvar_2022121416005547810))
        #最大化窗口
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2022121418505509625,Title:最大化窗口,Note:')
        tvar_2022121418505509726=iwin.do_win_maximize(waitfor=10.000,win_title=r'百度一下，你就知道')
        print('[Main] [最大化窗口] [SNTag:2022121418505509625]  返回值：[' + str(type(tvar_2022121418505509726)) + ']' + str(tvar_2022121418505509726))
        time.sleep(1)
        #设置文本
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2022121416024365211,Title:设置文本,Note:')
        iedge.set_element_val_edge(waitfor=10.000,text=self.keyword,title=r'百度一下，你就知道',url=r'https://www.baidu.com/',attrMap={"hasReachedRelativeAncestor":"false","nodeHierarchyInfo":[{"isPresentInSelector":1,"otherAttributes":{},"selectorInfo":{"attributes":{"css-selector":"#kw","id":"kw","tag":"INPUT","xpath":"//*[@id=\"kw\"]"},"index":0,"tagName":"INPUT"}}]})
        #鼠标点击
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2022121416060705116,Title:鼠标点击,Note:此处设置了前置延时，以避免网速慢，网页加载不完全的情况')
        time.sleep(3)
        iedge.do_click_pos_edge(waitfor=10.000,run_mode='unctrl',button='left',curson='center',continue_on_error='break',title=r'百度一下，你就知道',url=r'https://www.baidu.com/*',attrMap={"hasReachedRelativeAncestor":"false","nodeHierarchyInfo":[{"isPresentInSelector":1,"otherAttributes":{},"selectorInfo":{"attributes":{"css-selector":"#su","tag":"INPUT","type":"submit","xpath":"//*[@id=\"su\"]"},"index":0,"tagName":"INPUT"}}]})
        # For循环
        self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:2022121416264998315,Title:For循环,Note:')
        for i in [1,2,3,4]:
            #获取文本
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:202212141620368636,Title:获取文本,Note:可注意通配符 * 和元素 i 在网址及属性表的应用')
            title=iedge.get_element_val_edge(waitfor=10.000,title=r'*百度搜索',url=r'https://www.baidu.com*',continue_on_error='continue',attrMap={
                "hasReachedRelativeAncestor": "false",
                "nodeHierarchyInfo": [
                    {
                        "isPresentInSelector": 1,
                        "otherAttributes": {
                        },
                        "selectorInfo": {
                            "attributes": {
                                "aaname": "*",
                                "css-selector": "#"+str(i)+" > div:nth-child(1) > div:nth-child(1) > h3:nth-child(1) > a:nth-child(1)",
                                "parentid":str(i),
                                "tag": "A",
                                "xpath": "//*[@id=\""+str(i)+"\"]/div[1]/div[1]/h3[1]/a[1]"
                            },
                            "index": 0,
                            "tagName": "A"
                        }
                    }
                ]
            }
            )
            print('[Main] [获取文本] [SNTag:202212141620368636]  返回值：[' + str(type(title)) + ']' + str(title))
            #获取环境路径
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2022121511575246786,Title:获取环境路径,Note:不同电脑，桌面路径可能不同')
            file=tvar_2022121511575246887=tvar_2022121511575246887=rpa_environment.get_sys_path(name='Desktop')
            print('[Main] [获取环境路径] [SNTag:2022121511575246786]  返回值：[' + str(type(file)) + ']' + str(file))
            #文件是否存在
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2022121416341899533,Title:文件是否存在,Note:注意判断组件与if的配合使用')
            tvar_2022121416341899534=ifile.is_file_exist(dir_path=tvar_2022121511575246887,filename='RPA百度搜索结果'+str(datetime.date.today())+'.xlsx',is_fuzzy_matching=False,is_traverse=True)
            print('[Main] [文件是否存在] [SNTag:2022121416341899533]  返回值：[' + str(type(tvar_2022121416341899534)) + ']' + str(tvar_2022121416341899534))
            # IF分支
            self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:2022121416343043236,Title:IF分支,Note:')
            if tvar_2022121416341899534:
                pass
            else:
                #创建excel
                self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2022121416345041038,Title:创建excel,Note:')
                tvar_2022121416345041139=iexcel.create_excel(path=tvar_2022121511575246887,file_name='RPA百度搜索结果'+str(datetime.date.today()))
                print('[Main] [创建excel] [SNTag:2022121416345041038]  返回值：[' + str(type(tvar_2022121416345041139)) + ']' + str(tvar_2022121416345041139))
                #单元格写入
                self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2022121416414711656,Title:单元格写入,Note:')
                tvar_2022121416414711757=iexcel.write_cell(path=tvar_2022121416345041139,text='序号',file_type='file')
                print('[Main] [单元格写入] [SNTag:2022121416414711656]  返回值：[' + str(type(tvar_2022121416414711757)) + ']' + str(tvar_2022121416414711757))
                #单元格写入
                self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2022121416424964659,Title:单元格写入,Note:')
                tvar_2022121416424964660=iexcel.write_cell(path=tvar_2022121416345041139,text='标题',cell='B1',file_type='file')
                print('[Main] [单元格写入] [SNTag:2022121416424964659]  返回值：[' + str(type(tvar_2022121416424964660)) + ']' + str(tvar_2022121416424964660))
            #单元格写入
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2022121416402603452,Title:单元格写入,Note:注意文件和单元格的定义方式，可引入函数及流程前期已定义参数')
            tvar_2022121416402603553=iexcel.write_cell(path=file+'\\RPA百度搜索结果'+str(datetime.date.today())+'.xlsx',text=i,cell='A'+str(i+1),file_type='file')
            print('[Main] [单元格写入] [SNTag:2022121416402603452]  返回值：[' + str(type(tvar_2022121416402603553)) + ']' + str(tvar_2022121416402603553))
            #单元格写入
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:20221215135635158119,Title:单元格写入,Note:')
            tvar_20221215135635158120=iexcel.write_cell(path=file+'\\RPA百度搜索结果'+str(datetime.date.today())+'.xlsx',text=title,cell='B'+str(i+1),file_type='file')
            print('[Main] [单元格写入] [SNTag:20221215135635158119]  返回值：[' + str(type(tvar_20221215135635158120)) + ']' + str(tvar_20221215135635158120))
        #文件
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2022121610210804725,Title:文件,Note:')
        time.sleep(5)
        ics.run_shellexecute(path=file+'\\RPA百度搜索结果'+str(datetime.date.today())+'.xlsx')
 
if __name__ == '__main__':
    ILog.begin_init()
    robot_no = ''
    proc_no = ''
    job_no = ''
    input_arg = ''
    try:
        argv = sys.argv[1:]
        opts, args = getopt.getopt(argv,"hr:p:j:i:",["robot = ","proc = ","job = ","input = "])
    except getopt.GetoptError:
        print ('robot.py -r <robot> -p <proc> -j <job>')
    for opt, arg in opts:
        if opt == '-h':
            print ('robot.py -r <robot> -p <proc> -j <job>')
        elif opt in ("-r", "--robot"):
            robot_no = arg
        elif opt in ("-p", "--proc"):
            proc_no = arg
        elif opt in ("-j", "--job"):
            job_no = arg
        elif opt in ("-i", "--input"):
            input_arg = arg
    pro = GetBaiduRankList(robot_no=robot_no,proc_no=proc_no,job_no=job_no,input_arg=input_arg)
    pro.Main()
